import  crypto from 'crypto';

/**
 * Create token by uid. Encrypt uid and timestamp to get a token.
 *
 * @param  {String} uid user id
 * @param  {String|Number} timestamp
 * @param  {String} password 
 * @param  {String} salt
 * @return {String}     token string
 */
export const create = function(uid, timestamp, password, salt) {
    var msg = uid + '|' + timestamp + '|' + password;
    var cipher = crypto.createCipher('aes256', salt);
    var enc = cipher.update(msg, 'utf8', 'hex');
    enc += cipher.final('hex');
    return enc;
};

/**
 * Parse token to validate it and get the uid and timestamp.
 *
 * @param  {String} token token string
 * @param  {String} salt   decrypt password
 * @return {Object}  {uid: xx, timestamp: xx, password: xx}
 */
export const parse = function(token, salt) {
    var decipher = crypto.createDecipher('aes256', salt);
    var dec;
    try {
        dec = decipher.update(token, 'hex', 'utf8');
        dec += decipher.final('utf8');
    } catch(err) {
        console.error('[token] fail to decrypt token. %j', token);
        return null;
    }
    var ts = dec.split('|');
    if(ts.length !== 3) {
        // illegal token
        return null;
    }
    return {uid: ts[0], timestamp: Number(ts[1]), password: ts[2]};
};